package com.i2works.smartluolong.utils.common;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Base64;

/**
 * 图片转换工具类
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/7/12 16:37
 */

public class ImageConverUtil {

    /**
     * 图片文件转换成base64
     *
     * @param imagePath 待处理的图片
     */
    public static String toBase64(String imagePath) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        InputStream in;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(imagePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        if (null != data && data.length > 0) {
            //返回Base64编码过的字节数组字符串
            return Base64.getEncoder().encodeToString(data);
        } else {
            return null;
        }
    }

    /**
     * 将base转换成图片
     *
     * @param base64Code 图片base64代码
     * @param imagePath  新生成的图片
     */
    public static Boolean toFile(String base64Code, String imagePath) {
        //对字节数组字符串进行Base64解码并生成图片
        if (base64Code == null)
            return false;
        try {
            String code = base64Code.replace(" ", "");
            //Base64解码
            byte[] b = Base64.getDecoder().decode(code);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //创建完整路径
            File destFile = new File(imagePath);
            if (!destFile.exists()) {
                destFile.mkdirs();
            }
            OutputStream out = new FileOutputStream(imagePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 将iamge对象转换成base64
     *
     * @param image  image对象
     * @param width  宽度
     * @param height 高度
     */
    public static String toBase64(Image image) throws IOException {
        return executeBase64(image, 0, 0);
    }

    /**
     * 将iamge对象转换成base64（带剪裁）
     *
     * @param image  image对象
     * @param width  宽度
     * @param height 高度
     */
    public static String toBase64(Image image, int width, int height) throws IOException {
        return executeBase64(image, width, height);
    }

    /**
     * iamge对象转换成base64实际执行方法
     */
    private static String executeBase64(Image image, int width, int height) throws IOException {
        // Image->bufferreImage
        BufferedImage bimg;
        if (width == 0 || height == 0) {
            bimg = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        } else {
            bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        }
        Graphics g = bimg.createGraphics();
        g.drawImage(image, 0, 0, null);
        g.dispose();
        // bufferImage->base64
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bimg, "jpg", outputStream);
        return Base64.getEncoder().encodeToString(outputStream.toByteArray());
    }
}
